import React, { useState, useEffect } from 'react';
import { Table, Card, Button, Input, Space, message, Pagination, Layout, Tooltip } from 'antd';
import { SearchOutlined, EyeOutlined, ArrowLeftOutlined, ReloadOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import userService from '../../services/userService';
import type { User, PaginationParams } from '../../services/userService';
import { getFormattedErrorMessage } from '../../services/baseApi';
import './UsersPage.css';

const { Search } = Input;

const UsersPage: React.FC = () => {
  const navigate = useNavigate();
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [pagination, setPagination] = useState({
    page: 1,
    pageSize: 20
  });

  // 返回首页
  const handleBack = () => {
    navigate('/dashboard');
  };

  // 加载用户列表
  const loadUsers = async (params?: PaginationParams) => {
    setLoading(true);
    try {
      const response = await userService.getUserList(params || pagination);
      if (response.code === 0) {
        setUsers(response.data.list);
        setTotal(response.data.pagination.total);
      } else {
        message.error(response.message || '获取用户列表失败');
      }
    } catch (error) {
      message.error(getFormattedErrorMessage(error));
    } finally {
      setLoading(false);
    }
  };

  // 页面初始化加载
  useEffect(() => {
    loadUsers();
  }, []);

  // 翻页处理
  const handlePageChange = (page: number, pageSize: number) => {
    const newPagination = { page, pageSize };
    setPagination(newPagination);
    loadUsers(newPagination);
  };

  // 查看用户详情
  const handleViewDetail = (userId: number) => {
    navigate(`/users/${userId}`);
  };

  // 表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: 'UUID',
      dataIndex: 'uuid',
      key: 'uuid',
      width: 280,
      render: (uuid: string) => (
        <span style={{ fontFamily: 'monospace', fontSize: '12px' }}>{uuid}</span>
      ),
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      width: 150,
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      key: 'mobile',
      width: 140,
      render: (mobile: string) => mobile || '-',
    },
    {
      title: '余额',
      dataIndex: 'balance',
      key: 'balance',
      width: 120,
      render: (balance: number) => (
        <span style={{ color: '#52c41a', fontWeight: 'bold' }}>
          ¥{balance.toFixed(2)}
        </span>
      ),
    },
    {
      title: '积分',
      dataIndex: 'credit',
      key: 'credit',
      width: 100,
      render: (credit: number) => (
        <span style={{ color: '#1890ff', fontWeight: 'bold' }}>
          {credit}
        </span>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (record: User) => (
        <Space size="small">
          <Button
            type="primary"
            icon={<EyeOutlined />}
            size="small"
            onClick={() => handleViewDetail(record.id)}
          >
            详情
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <Layout className="users-layout">
      {/* 统一页头 */}
      <div className="users-header">
        <div className="header-left">
          <Button 
            className="back-button" 
            type="text" 
            icon={<ArrowLeftOutlined />} 
            size="large" 
            onClick={handleBack} 
          />
          <h1 className="page-title">会员管理</h1>
        </div>
        <div className="header-right">
          <Search
            placeholder="搜索用户名或手机号"
            allowClear
            enterButton={<SearchOutlined />}
            style={{ width: 300 }}
            onSearch={(value) => {
              // 这里可以添加搜索逻辑
              console.log('搜索:', value);
            }}
          />
          <Tooltip title="刷新数据">
            <Button 
              icon={<ReloadOutlined />}
              onClick={() => loadUsers()}
            >
              刷新
            </Button>
          </Tooltip>
        </div>
      </div>

      {/* 主要内容区域 */}
      <div className="users-content">
        <Card>
          <Table
            columns={columns}
            dataSource={users}
            rowKey="id"
            loading={loading}
            pagination={false}
            scroll={{ x: 1200 }}
            size="middle"
          />

          <div style={{ marginTop: '16px', textAlign: 'right' }}>
            <Pagination
              current={pagination.page}
              pageSize={pagination.pageSize}
              total={total}
              showSizeChanger
              showQuickJumper
              showTotal={(total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`}
              onChange={handlePageChange}
              onShowSizeChange={handlePageChange}
              pageSizeOptions={['10', '20', '50', '100']}
            />
          </div>
        </Card>
      </div>
    </Layout>
  );
};

export default UsersPage; 